<?php
/**
 * Created by PhpStorm.
 * User: kendy
 * Date: 2019/10/14
 * Time: 11:23
 */
namespace app\admin\model;
use think\Model;
use think\Db;
class Settlements extends Model
{
    // 确定链接表名
    protected $name = 'settlements';
    /**
     * 根据搜索条件获取所有的商家待结算数据
     * @param $where  查询条件
     * @param $offset
     * @param $limit
     * @return mixed
     */
    public function getNoSettleList($where ,$offset, $limit)
    {
       $type = input('param.type'); 
       $shop_name = (!empty(input('param.shop_name')))?input('param.shop_name'):'';
        $hotel =[];
        $tour = [];
        $team = [];
       if(!empty($shop_name)){
          $hotel['hotel_name'] = ['like','%'.$shop_name.'%'];
          $tour['tour_name'] = ['like','%'.$shop_name.'%'];
          $team['team_name'] = ['like','%'.$shop_name.'%'];
       }

	   //酒店待结算的数据 
       $hotelList = Db::name('hotel')
	   ->field('hotel_id as id,hotel_name as name,hotel_tel as tel,no_settled_order_num,procedure_fee')
	   ->where($where)
     ->where($hotel)
	   ->select();
	   foreach($hotelList as $key=>$val)
	   { $hotelList[$key]['type'] = 1; }
	   //景点待结算的数据 
	   $tourList = Db::name('tours')
	   ->field('tour_id as id,tour_name as name,tour_tel as tel,no_settled_order_num,procedure_fee')
	   ->where($where)
      ->where($tour)
	   ->select();
	   foreach($tourList as $key=>$val)
	   { $tourList[$key]['type'] = 2; }
	   //旅行社待结算的数据 
	   $teamList = Db::name('team')
	   ->field('team_id as id,team_name as name,team_phone as tel,no_settled_order_num,procedure_fee')
	   ->where($where)
      ->where($team)
	   ->select(); 
	   foreach($teamList as $key=>$val)	
	   { $teamList[$key]['type'] = 3; } 
      if($type==1) {$tourList = [];$teamList = [];}
      if($type==3) {$hotelList = [];$teamList = [];}
      if($type==4) {$hotelList = [];$tourList = [];}
      $resultData = array_merge($hotelList,$tourList,$teamList);    
	    return ['rd'=>$resultData,'count'=>count($resultData)];
    }
    /**
     * [getSettledList 获取已结算未打款的商家信息]
     * @Author   kendy
     * @DateTime 2020-04-13T16:14:31+0800
     * @return   [type]                   [description]
     */
   public function getSettledList($where,$offset,$limit)
   {
  
       //查看当前结算表没有打款的
       $shop_name = (!empty(input('param.shop_name')))?input('param.shop_name'):'';
       $hotel =[];
       $tour = [];
       $team = [];
       if(!empty($shop_name)){
            $hotel['hotel_name'] = ['like','%'.$shop_name.'%'];
            $tour['tour_name'] = ['like','%'.$shop_name.'%'];
            $team['team_name'] = ['like','%'.$shop_name.'%'];
         } 
        $noPaymentLists = Db::name('settlements')
        ->field('s.settlement_id,s.settlement_id,s.settlement_no,settlement_type,object_id,object_type,settlement_money,commission_fee,back_money,settlement_status,settlement_form,settlement_time,r.receipt,r.time,r.admin_id,a.admin_relname')
        ->alias("s")
        ->join("remit r",'s.settlement_id = r.settlement_id','left')  
        ->join("admin a",'r.admin_id = a.admin_id','left')  
        ->where($where)
        ->order('settlement_time asc')
        ->limit($offset,$limit)
        ->select(); 
        if(count($noPaymentLists)>0){
        foreach ($noPaymentLists as $key => $value) {
            if($value['object_type'] == 1){
                $shopInfo = Db::name('hotel')
                ->field("hotel_name as name,hotel_id as id,hotel_tel as tel")
                ->where(['hotel_id'=>$value['object_id']])
                ->where($hotel)
                ->find(); 
            } 
            if($value['object_type'] == 2){ 
                $shopInfo = Db::name('tours')
                ->field("tour_name as name,tour_id as id,tour_tel as tel")
                ->where(['tour_id'=>$value['object_id']])
                ->where($tour)
                ->find(); 
            }
            if($value['object_type'] == 3){ 
                $shopInfo = Db::name('team')
                ->field("team_id as id,team_phone as tel,team_name as name")
                ->where(['team_id'=>$value['object_id']])
                ->where($team)
                ->find(); 
            }
                $noPaymentLists[$key]['name'] = $shopInfo['name'];
                $noPaymentLists[$key]['tel'] = $shopInfo['tel']; 
                $noPaymentLists[$key]['id'] = $shopInfo['id'];
                $noPaymentLists[$key]['settlement_time'] = date('Y-m-d H:i:s',$value['settlement_time']); 
                $noPaymentLists[$key]['settlement_type'] = getSettlementType($value['settlement_type']);
        }

      } 
      $count = Db::name('settlements')->where($where)->select();
      return ['rd'=>$noPaymentLists,'count'=>count($count)];  
   }
  
   public function getshopBankList($where ,$offset, $limit)
    {
       $type = input('param.type'); 
       $shop_name = (!empty(input('param.shop_name')))?input('param.shop_name'):'';
        $hotel =[];
        $tour = [];
        $team = [];
       if(!empty($shop_name)){
          $hotel['hotel_name'] = ['like','%'.$shop_name.'%'];
          $tour['tour_name'] = ['like','%'.$shop_name.'%'];
          $team['team_name'] = ['like','%'.$shop_name.'%'];
       }

     //酒店待结算的数据 
       $hotelList = Db::name('hotel')
     ->field('hotel_name as name,bank_user_name,hotel_bank_card as bank_card,hotel_bank_name as bank_name')
     ->where($where)
     ->where($hotel)
     ->select();
     foreach($hotelList as $key=>$val)
     { $hotelList[$key]['type'] = 1; }
     //景点待结算的数据 
     $tourList = Db::name('tours')
     ->field('tour_name as name,bank_user_name,tour_bank_name as bank_name,tour_bank_card as bank_card')
     ->where($where)
      ->where($tour)
     ->select();
     foreach($tourList as $key=>$val)
     { $tourList[$key]['type'] = 2; }
     //旅行社待结算的数据 
     $teamList = Db::name('team')
     ->field('team_name as name,team_bank_card as bank_card,team_bank_name as bank_name,bank_user_name')
     ->where($where)
      ->where($team)
     ->select(); 
     foreach($teamList as $key=>$val) 
     { $teamList[$key]['type'] = 3; } 
      if($type==1) {$tourList = [];$teamList = [];}
      if($type==2) {$hotelList = [];$teamList = [];}
      if($type==3) {$hotelList = [];$tourList = [];}
      $resultData = array_merge($hotelList,$tourList,$teamList);    
      return ['rd'=>$resultData,'count'=>count($resultData)];
    } 

   /**
    * [generateSettle 生成结算订单]
    * @Author   kendy
    * @DateTime 2020-01-03T10:29:41+0800
    * @return   [type]                   [description]
    */
	public function generateSettle(){
		//$shopId = (int)input('param.data');
		$orderIdArr = [];
		$orderIdObject = input('param.data');
		$orderIdArr = json_decode($orderIdObject);
		$type = input('param.object_type');
		$shopId =input('param.object_id');
		//type为1时酒店待结 为2时景点待结算 为3时旅行社待结算
		if($type==1){$table = "hotel_order"; $shopName="hotel";$idField="hotel_id";}
		if($type==2){$table = "tour_order";  $shopName="tours";$idField="tour_id"; }
		if($type==3){$table = "gtour_order"; $shopName="team"; $idField="team_id";}

		$where['order_id'] = ['IN',$orderIdArr];
		$where['is_del'] = 0;
		$where['settlement_id'] = 0; 
       //查看是否有结算的订单
        $orders = Db::name($table)->where($where)->field("order_id,order_price,commission_fee")->select();   
        if(empty($orders)) 
      return ['code'=>0,'msg'=>"商家没有结算的订单"]; 
	    $settlementMoney = 0;
        $commissionFee = 0;
        $ids = [];
    	foreach ($orders as $key => $v) {
           $ids[] = $v['order_id']; 
           $settlementMoney += $v['order_price']; 
           $commissionFee += abs($v['commission_fee']);
    	}  
    	//无效的店铺信息 
        $shops = Db::name($shopName)->where(['is_del'=>0,'is_display'=>0,'is_pass'=>1,$idField=>$shopId])->find();  
       if(empty($shops)) return ['code'=>0,'msg'=>"无效的店铺信息"];  
       Db::startTrans();
       try{

           $data['settlement_type'] = 0;
           $data['object_id'] =  $shopId;
           $data['object_type'] = $type;
           $data['settlement_money'] = $settlementMoney; //商品总金额
           $data['commission_fee'] = $commissionFee; //结算应收的佣金
           $data['back_money'] = $settlementMoney-$commissionFee; //返回给商户的钱
           $data['settlement_status'] = 1;
           $data['settlement_time'] = time(); 
           $data['admin_id'] = session('admin_id');
           $settlementId = Db::name('settlements')->insertGetId($data);
           if($settlementId){ 
              $settlementNo = $settlementId.(fmod($settlementId,7));
              Db::name('settlements')
              ->where('settlement_id',$settlementId)
              ->update(['settlement_no'=>$settlementNo]);
              //修改商家订单情况
             Db::name($table)
             ->where(['order_id'=>['in',$ids]])
             ->update(['settlement_id'=>$settlementId]);
             //修改商家的未结算的订单数和未结算佣金数 
            $up['no_settled_order_num'] = 0; 
            $num_count = count($ids); 
            Db::name($shopName)->where(''.$idField.'',$shopId)->setDec("no_settled_order_num",$num_count); 
            if(!empty($commissionFee))
            Db::name($shopName)->where(''.$idField.'',$shopId)->setDec("no_settled_order_fee",$commissionFee);  

           }
            Db::commit(); 
         return ['code'=>1,'msg'=>'结算成功'];  
       }catch(\Exception $e){ 
          Db::rollback(); 
          return ['code'=>0,'msg'=>$e->getMessage()]; 
       } 
        return ['code'=>0,'msg'=>'结算失败'];  
    }

    /**
     * [doPayments 已打款]
     * @Author   kendy
     * @DateTime 2020-04-14T14:25:04+0800
     * @return   [type]                   [description]
     */
    public function doPayments(){ 
     // $orderIdArr = [];
      $settlementId = input('param.data');
     // $orderIdArr = json_decode($orderIdObject); 
      $receip = input('param.receip');
      $where['settlement_id'] = $settlementId; 
     
       //查看是否有结算的订单
      $settlementInfo = Db::name("settlements")
      ->where($where) 
      ->find();  
      if(empty($settlementInfo))
        return ['code'=>0,'msg'=>"无效的结算信息"];  
       Db::startTrans();
       try{ 
            Db::name("settlements")
            ->where($where)
            ->update(['is_payment'=>1]);

            //增加打款表
               $remit['settlement_id'] = $settlementId;
               $remit['receipt'] = $receip;
               $remit['time'] = date('Y-m-d H:i:s');
               $remit['admin_id'] =  session('admin_id');
               Db::name('remit')->insert($remit);  
              //增加一条资金变动信息
               $LogMoneys = [];
               $LogMoneys['target_type'] = 1;
               $LogMoneys['type'] = $settlementInfo['object_type'];
               $LogMoneys['target_id'] = $settlementInfo['object_id'];
               $LogMoneys['data_id'] = 1;
               $LogMoneys['data_src'] = 2;
               $LogMoneys['remark'] = "财务打款商户";
               $LogMoneys['money_type'] = 0;
               $LogMoneys['money'] = $settlementInfo['back_money'];
               $LogMoneys['create_time'] = date('Y-m-d H:i:s'); 
               Db::name('log_moneys')->insert($LogMoneys); 
            
             
            
            Db::commit(); 
         return ['code'=>1,'msg'=>'打款成功'];  
       }catch(\Exception $e){ 
          Db::rollback(); 
          return ['code'=>0,'msg'=>$e->getMessage()]; 
       } 
        return ['code'=>0,'msg'=>'打款失败'];  
    }


}